package com.fenfen.novel.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.fenfen.novel.NovelListActivity;
import com.fenfen.novel.R;
import com.fenfen.novel.adapter.CategoryAdapter;
import com.fenfen.novel.model.Category;
import com.fenfen.novel.rest.RestClient;

import org.parceler.Parcels;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NovelCategoryFragment extends Fragment implements CategoryAdapter.CategoryClickListener {

  private RecyclerView recyclerView;
  private CategoryAdapter adapter;
  private List<Category> categoryList = new ArrayList<>();
  private Call<List<Category>> call;

  public static NovelCategoryFragment newInstance(Bundle bundle) {
    NovelCategoryFragment fragment = new NovelCategoryFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_category, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_cateogry);
    GridLayoutManager lm = new GridLayoutManager(getActivity(), 3);
    recyclerView.setLayoutManager(lm);
    adapter = new CategoryAdapter(getActivity(), categoryList);
    adapter.setItemClickListener(this);
    recyclerView.setAdapter(adapter);
    loadData();
    return view;
  }

  public boolean isLoading() {
    return call != null && call.isExecuted();
  }

  public boolean hasData() {
    return adapter != null && adapter.getItemCount() > 0;
  }

  public void loadData() {
    if (isLoading()) {
      return;
    }
    call = RestClient.newInstance().getNovelService().showAllCateogrys();
    call.enqueue(new Callback<List<Category>>() {
      @Override
      public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
        List<Category> list = response.body();
        if (list != null && list.size() != 0) {
          adapter.setData(list);
        }
      }

      @Override
      public void onFailure(Call<List<Category>> call, Throwable t) {

      }
    });
  }


  @Override
  public void onItemClick(View v, Category category) {
    Intent intent = new Intent(getActivity(), NovelListActivity.class);
    intent.putExtra(NovelListActivity.EXTRA_CATEGORY, Parcels.wrap(category));
    startActivity(intent);
  }
}
